<template>
  <div class="app-container">
    <el-card class="mb20">
      <el-form inline :model="listQ">
        <el-form-item label="合同编号">
          <el-input
            v-model="listQ.contractNo"
            placeholder="合同编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="业务员">
          <el-select v-model="listQ.salesmanId" placeholder="业务员">
            <el-option
              v-for="item in saleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-select v-model="listQ.customerId" placeholder="客户名称">
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="交货日期">
          <el-date-picker
            v-model="listQ.deliveryAttr"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="送货方式">
          <el-select v-model="listQ1.deliveryMethod" placeholder="送货方式">
            <el-option label="快递" value="快递"></el-option>
            <el-option label="物流" value="物流"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期">
          <el-date-picker
            v-model="listQ.signAttr"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人">
          <el-select v-model="listQ.applyUser" placeholder="申请人">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="listQ.applyAttr"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select v-model="listQ1.applyStatus" placeholder="申请状态">
            <el-option label="未提交" value="未提交"></el-option>
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="已审核" value="已审核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人">
          <el-select v-model="listQ.approveUser" placeholder="审核人">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
            v-model="listQ.approveAttr"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="listQ1.approveStatus" placeholder="审核状态">
            <el-option label="通过" value="通过"></el-option>
            <el-option label="驳回" value="驳回"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button @click="handleReset('listQ', 'getList')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="success" @click="handleAdd">新增</el-button>
      <el-button
        :disabled="delArray.length == 0"
        type="danger"
        plain
        @click="handleDel(true)"
        >删除</el-button
      >
      <el-table @selection-change="handleChange" :data="list">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          v-for="item in listC"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        ></el-table-column>
        <el-table-column label="操作" width="220px" v-slot="{ row }">
          <el-button size="mini" type="primary" @click="handleEdit(row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" @click="handleDel(false, row)"
            >删除</el-button
          >
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right; margin-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pager.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pager.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      width="1400px"
      center
      :visible.sync="visible"
      :title="title"
      @close="close"
    >
      <el-form inline :model="listE" ref="listERef">
        <el-form-item label="订单编号" prop="orderNo" required>
          <el-input
            disabled
            v-model="listE.orderNo"
            placeholder="订单"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="OpenDialog1">选择</el-button>
        </el-form-item>
        <el-form-item label="送货方式" prop="deliveryMethod" required>
          <el-select v-model="listE.deliveryMethod" placeholder="送货方式">
            <el-option value="快递" label="快递"></el-option>
            <el-option value="物流" label="物流"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" prop="deliveryAddress" required>
          <el-input
            v-model="listE.deliveryAddress"
            placeholder="收货地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact" required>
          <el-input v-model="listE.contact" placeholder="联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" required>
          <el-input v-model="listE.phone" placeholder="联系方式"></el-input>
        </el-form-item>
        <el-form-item label="签订日期" prop="signDate" required>
          <el-date-picker
            v-model="listE.signDate"
            type="datetime"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="listE.remark"
            type="textarea"
            :rows="3"
            resize="none"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-button @click="handleAdd2" type="success">新增</el-button>
      <el-table :data="listE.detailList">
        <el-table-column v-slot="{ $index }">{{ $index + 1 }}</el-table-column>
        <el-table-column
          v-for="item in detailListC"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          v-slot="{ row }"
        >
          <template v-if="item.prop == 'material.name'">
            <span>{{ row.material.name }}</span>
            <el-button type="primary" @click="OpenDialog2(row)">选择</el-button>
          </template>
          <template v-else-if="item.prop == 'material.model'">
            <span>{{ row.material.name }}</span>
          </template>
          <template v-else-if="item.prop == 'material.specification'">
            <span>{{ row.material.specification }}</span>
          </template>
          <template v-else-if="item.prop == 'material.unit'">
            <span>{{ row.material.unit }}</span>
          </template>
          <template v-else-if="item.prop == 'price'">
            <el-input-number
              v-model="row.price"
              size="mini"
              :min="0"
            ></el-input-number>
          </template>
          <template v-else-if="item.prop == 'quantity'">
            <el-input-number
              v-model="row.quantity"
              size="mini"
              :min="1"
            ></el-input-number>
          </template>
          <template v-else-if="item.prop == 'amount'">
            <span>{{ (row.amount = row.price * row.quantity) }}</span>
          </template>
          <template v-else>
            <el-input v-model="row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="操作" v-slot="{ $index }">
          <el-button
            size="mini"
            type="success"
            @click="handleAdd1($index)"
            plain
            >添加</el-button
          >
          <el-button size="mini" type="danger" @click="handleDel1($index)" plain
            >删除</el-button
          >
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="close">取消</el-button>
          <el-button @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="选择订单编号"
      center
      @close="visible1 = false"
      :visible.sync="visible1"
    >
      <el-card class="mb20">
        <el-form inline :model="listQ1">
          <el-form-item label="订单编号">
            <el-input
              v-model="listQ1.orderNo"
              placeholder="订单编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input
              v-model="listQ1.customerName"
              placeholder="客户名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList1">搜索</el-button>
            <el-button @click="handleReset('listQ1', 'getList1')"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="list1">
          <el-table-column
            v-for="item in listC1"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
          ></el-table-column>
          <el-table-column label="操作" width="220px" v-slot="{ row }">
            <el-button size="mini" type="primary" @click="submit1(row)"
              >选择</el-button
            >
          </el-table-column>
        </el-table>
        <el-pagination
          style="text-align: right; margin-top: 20px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pager.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pager.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
        >
        </el-pagination>
      </el-card>
    </el-dialog>
    <el-dialog
      title="选择物料档案"
      center
      @close="visible2 = false"
      :visible.sync="visible2"
    >
      <el-row>
        <el-col :span="4">
          <el-tree
            :data="materialCategory"
            :props="{ label: 'name', value: 'id' }"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-col>
        <el-col :span="20">
          <el-table :data="materialList">
            <el-table-column
              v-for="item in materialListC"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            ></el-table-column>
            <el-table-column label="操作" width="220px" v-slot="{ row }">
              <el-button size="mini" type="primary" @click="submit2(row)"
                >选择</el-button
              >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getSaleContractList, getSalesManList, EditSaleContract, AddSaleContract, DelSaleContract } from '@/api_zc/scm/sale-management/sale-contract'
import { getSaleOrderList, getApplyApproveUserList } from '@/api_zc/scm/sale-management/sale-order'
import { getCustomerList } from '@/api_zc/task/sale-order-approve'
import { getMaterialCatgoryChildrenList } from '@/api_zc/wms/material-category'
import { getMaterialList } from '@/api_zc/scm/sale-management/sale-order'
export default {
  mounted () {
    this.getList()
    this.getList1()
    this.getUnity()
    this.getMaterialList()
  },
  data () {
    return {
      list: [],
      pager: {
        page: 1,
        limit: 10,
        total: 0
      },
      listQ: {
        contractNo: '',
        orderId: '',
        customerId: '',
        salesmanId: '',
        deliveryStartDate: "",
        deliveryEndDate: '',
        deliveryAttr: [],
        deliveryMethod: '',
        signStartDate: '',
        signEndDate: "",
        signAttr: [],
        applyUser: '',
        applyStartTime: '',
        applyAttr: [],
        applyEndTime: '',
        applyStatus: '',
        approveUser: '',
        approveStartTime: '',
        approveEndTime: '',
        approveAttr: [],
        approveStatus: '',
      },
      listC: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '订单编号',
          prop: 'order.orderNo'
        },
        {
          label: '客户名称',
          prop: 'customer.name'
        },
        {
          label: '联系人',
          prop: 'contact'
        },
        {
          label: '联系方式',
          prop: 'phone'
        },
        {
          label: '金额合计',
          prop: 'totalAmount'
        },
        {
          label: '交货日期',
          prop: 'deliveryDate'
        },
        {
          label: '申请人',
          prop: 'applyUser.realName'
        },
        {
          label: '申请时间',
          prop: 'applyTime'
        },
        {
          label: '申请状态',
          prop: 'applyStatus'
        },
        {
          label: '审核人',
          prop: 'approveUser.realName'
        },
        {
          label: '审核时间',
          prop: 'approveTime'
        },
        {
          label: '审核状态',
          prop: 'approveStatus'
        },
      ],
      listE: {
        orderId: null,
        orderNo: null,
        deliveryMethod: null,
        deliveryAddress: null,
        contact: null,
        phone: null,
        signDate: null,
        remark: null
      },
      title: '',
      visible: false,

      list1: [],
      pager1: {
        page: 1,
        limit: 10,
        total: 0
      },
      listQ1: {
        orderNo: "",
        customerName: ''
      },
      listC1: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '订单编号',
          prop: 'orderNo'
        },
        {
          label: '客户名称',
          prop: 'customer.name'
        },
        {
          label: '金额合计',
          prop: 'totalAmount'
        },
        {
          label: '交货日期',
          prop: 'deliveryDate'
        },
      ],
      visible1: false,
      visible2: false,
      customerList: [],
      saleList: [],
      userList: [],
      materialList: [],
      materialCategory: [],
      detailListC: [
        {
          label: '产品',
          prop: 'material.name'
        },
        {
          label: '型号',
          prop: 'material.model'
        },
        {
          label: '规格',
          prop: 'material.specification'
        },
        {
          label: '单位',
          prop: 'material.unit'
        },
        {
          label: '单价',
          prop: 'price'
        },
        {
          label: '订货数量',
          prop: 'quantity'
        },
        {
          label: '金额',
          prop: 'amount'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
      materialListC: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '物料编号',
          prop: 'code'
        },
        {
          label: '物料名称',
          prop: 'name'
        },
        {
          label: '型号',
          prop: 'model'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '类型',
          prop: 'type'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
      materialPid: 0,
      detailListId: 0,
      visible: false,
      delArray: []
    }
  },
  methods: {
    async getUnity () {
      const data1 = await getCustomerList()
      this.customerList = data1.data.content
      const data2 = await getSalesManList()
      this.saleList = data2.data
      const data3 = await getApplyApproveUserList()
      this.userList = data3.data
      const data5 = await getMaterialCatgoryChildrenList()
      this.materialCategory = [
        {
          name: '目录',
          id: 0,
          children: data5.data
        }
      ]
    },
    handleNodeClick (val) {
      this.materialPid = val.id
      this.getMaterialList()
    },
    async getMaterialList () {
      const data4 = await getMaterialList({ pid: this.materialPid })
      this.materialList = data4.data.content
    },
    async getList () {
      // 时间选择器清空时会将字段置空，下面数组解构赋值会报错
      if (!this.listQ.deliveryAttr) {
        return
      }
      if (!this.listQ.signAttr) {
        return
      }
      if (!this.listQ.applyAttr) {
        return
      }
      if (!this.listQ.approveAttr) {
        return
      }
      [this.listQ.deliveryStartDate, this.listQ.deliveryEndDate] = this.listQ.deliveryAttr;
      [this.listQ.signStartDate, this.listQ.signEndDate] = this.listQ.signAttr;
      [this.listQ.applyStartTime, this.listQ.applyEndTime] = this.listQ.applyAttr;
      [this.listQ.approveStartTime, this.listQ.approveEndTime] = this.listQ.approveAttr
      const { data: { total, content } } = await getSaleContractList({ ...this.listQ, page: this.pager.page, limit: this.pager.limit })
      this.pager.total = total
      this.list = content
    },
    async getList1 () {
      const { data: { total, content } } = await getSaleOrderList({ ...this.listQ1, page1: this.pager.page, limit1: this.pager.limit })
      this.pager1.total = total
      this.list1 = content
    },
    close () {
      this.visible = false
    },
    handleEdit (row) {
      this.getList()
      this.visible = true
      this.isAdd = false
      this.title = '修改销售合同'
      this.$nextTick(() => {
        Object.assign(this.listE, {
          ...row,
          orderNo: row.order.orderNo
        })
      })
    },
    handleAdd () {
      this.getList()
      this.visible = true
      this.isAdd = true
      this.title = '添加销售合同'
      this.$nextTick(() => {
        this.$refs.listERef.resetFields()
        this.listE.detailList = []
      })
    },
    handleDel (flag, row) {
      let ids, tip
      if (flag) {
        ids = this.delArray.map(item => item.id)
        tip = this.delArray.map(item => item.order.orderNo).join(',')
      } else {
        ids = [row.id]
        tip = row.order.orderNo
      }
      this.$confirm(`是否确认删除销售合同编号为${tip}的数据项？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await DelSaleContract({ ids })
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    OpenDialog1 () {
      this.visible1 = true
    },
    OpenDialog2 (row) {
      this.detailListId = row.id
      this.visible2 = true
    },
    submit () {
      this.listE.deliveryDate = new Date(this.listE.deliveryDate)
      this.listE.applyTime = new Date(this.listE.applyTime)
      this.listE.approveTime = new Date(this.listE.approveTime)
      this.listE.signDate = new Date(this.listE.signDate)
      this.$refs.listERef.validate(async (callback) => {
        if (!callback) {
          return this.$message.error('请填写必要字段')
        }
        if (this.isAdd) {
          await AddSaleContract(this.listE)
          this.$message.success('添加成功')
        } else {
          await EditSaleContract(this.listE)
          this.$message.success('修改成功')
        }
        this.visible = false
        this.getList()
      })
    },
    submit1 (row) {
      this.listE.orderNo = row.orderNo
      this.listE.orderId = row.id
      this.visible1 = false
    },
    submit2 (row) {
      row.category = ''
      this.listE.detailList.find(item => {
        return this.detailListId == item.id
      }).material = row
      this.visible2 = false
    },
    handleSizeChange (val) {
      this.pager.limit = val
      this.getList()
    },
    handleSizeChange1 (val) {
      this.pager1.limit = val
      this.getList1()
    },
    handleCurrentChange (val) {
      this.pager.page = val
      this.getList()
    },
    handleCurrentChange1 (val) {
      this.pager1.page = val
      this.getList1()
    },
    handleReset (string, string1) {
      Object.assign(this[string], this.$options.data()[string])
      this[string1]()
    },
    handleChange (val) {
      this.delArray = val
    },
    handleDel1 (index) {
      this.listE.detailList.splice(index, 1)
    },
    handleAdd2 () {
      this.listE.detailList.push({
        material: {
        },
        price: 0,
        quantity: 0,
        amount: 0,
        remark: ''
      })
    },
    handleAdd1 (index) {
      this.listE.detailList.splice(index + 1, 0, {
        material: {
        },
        price: 0,
        quantity: 0,
        amount: 0,
        remark: ''
      })
    }
  }
} 
</script>

<style>
</style>